

/**
 * MacAddress stores an Ethernet MAC address as a String and provides
 * methods for comparison between two MAC addresses.
 * 
 * @author 
 *
 */
// TODO: Exceptions?
public class MacAddress implements Comparable<MacAddress> {

	private String address;

	/**
	 * Creates a MacAddress using the specified byte array.
	 * The address is stored as a String without delimiters.
	 * 
	 * @param addressAsBytes - The array of bytes containing the MacAddress values.
	 */
	public MacAddress(byte[] addressAsBytes) {

		String result = "";

		for (int i = 0; i < addressAsBytes.length; i++) {
			// Pad a leading '0' to single-digit values of the pair.
			if (addressAsBytes[i] < -112) {
				result += "0";
			}

			/* Adjust the value of the pair by 128 so the range is 0 to 255.
			 * and represent the pair's value as a hex string.
			 */
			result += Integer.toHexString((addressAsBytes[i] + 128));
		}

		// Store the address as a String.
		address = result;
	}

	/**
	 * Creates a MacAddress using the reserved address for broadcast.
	 * ff:ff:ff:ff:ff:ff
	 * The address is stored as a String without delimiters.
	 */
	public MacAddress() {
		// Special address for broadcast. ff:ff:ff:ff:ff:ff
		// Representing ff as a byte.

		address = "ffffffffffff";
	}

	/**
	 * Returns a String representation of a MacAddress with the six octets
	 * of an Ethernet MAC address separated by a ':'.
	 * 
	 * @return Returns a String representation of a MacAddress.
	 */
	public String toString() {
		String result = "";

		// Separate the six pairs with a ':'.
		int index = 0;

		// The first 5 pairs.
		for (int i = 0; i < 5; i++) {	
			result += address.substring(index, index + 2) + ":";
			index += 2;
		}

		// The sixth pair.
		result += address.substring(index, index + 2);

		return result;
	}

	/**
	 * Compares two MacAddresses.
	 * 
	 * @param otherAddress - The address being compared.
	 * @return Returns a negative integer, zero, or a positive integer if this address
	 *         is less than, equal to, or greater than the address being compared.
	 */
	@Override
	public int compareTo(MacAddress otherAddress) {

		if (address.compareTo(otherAddress.address) < 0) {
			return -1;
		} else if (address.compareTo(otherAddress.address) > 0) {
			return 1;
		}

		return 0;
	}
	
	/**
	 * Indicates whether one MacAddress is equal to another.
	 * 
	 * @param object - The object with which to compare.
	 * @return Returns <B>true</B> if the MacAddresses match.
	 *         Returns <B>false</B> otherwise. 
	 */
	@Override
	public boolean equals(Object object) {
		
		MacAddress otherAddress = (MacAddress)object;
		
		return address.equals(otherAddress.address);
	}

}
